/**
 * Created by LeungZ on 2016/8/22.
 */
class Log {
    constructor(containers ,$modalInstance, podSrv, ctgNotification, $timeout, $window, $stateParams, $scope) {
        'ngInject';
        this._modalInstance = $modalInstance;
        this._podSrv = podSrv;
        this._timeout = $timeout;
        this._notification = ctgNotification;
        this.timer= "";
        this.name = $stateParams.name;
        this.namesp = $stateParams.namesp;
        this.kDbCode = $stateParams.kDbCode;
        this.maxPage = 0;

        this.page = {
            currentPage: 0,
            totalItems: 0
        };

        if(containers && containers.length){
            this.containers = containers;
            this.contName = containers[0].name;
            this.getList();
        }

        $timeout(function () {
            angular.element('.well.well-sm').css({
                'max-height': ($window.innerHeight - 190) + 'px',
                'overflow-y': 'scroll'
            });
        }, 0, false);

        $scope.$on('$destroy', ()=> {
            this._timeout.cancel(this.timer);
        });
    }

    getList() {
        this._timeout.cancel(this.timer);
        if(this.page.currentPage == this.maxPage) this.page.currentPage = 0;

        this._podSrv.getLog({
            contName: this.contName,
            page: this.page.currentPage,
            namesp: this.namesp,
            podName: this.name,
            code: this.kDbCode
        }).then(data=> {
            this.logs = data.logs;
            this.page.totalItems = data.logNum;
            if(!this.maxPage){
                this._timeout(function(){
                    angular.element('.well.well-sm').scrollTop(angular.element('.well.well-sm')[0].scrollHeight);
                },0,false);
            }
            if(!this.page.currentPage){
                this.maxPage = Math.ceil(data.logNum / 200);
                this.page.currentPage = this.maxPage;
            }
            this.timer = this._timeout(this.getList.bind(this),10000);
        }).catch(()=> {
            this._notification.error('获取容器日志有误.');
        })
    }

    cancel() {
        this._modalInstance.dismiss('cancel');
    }
}


export default Log